package rjeutsky.validators;

import java.sql.SQLException;

import rjeutsky.database.interfaces.Repository;
import rjeutsky.models.User;
import rjeutsky.validators.interfaces.Validator;

public class UserValidator implements Validator<User> {

	private String errorMessages;
	private Repository repository;
	
	public UserValidator (Repository repository) {
		this.repository = repository;
	}
	
	@Override
	public boolean validate(User user) {
		StringBuilder errorBuilder = new StringBuilder();
		boolean validationResult = true;
		
		if (user.getLogin() == null || user.getLogin().isEmpty()) {
			validationResult = false;
			errorBuilder.append("login is required");
		} 
		else {
			if (user.getLogin().length() > 50) {
				validationResult = false;
				errorBuilder.append("login length must be < 50");
			}
		}
		
		try {
			if (!repository.isLoginUnique(user.getLogin())) {
				validationResult = false;
				errorBuilder.append("login is not unique");
			}
		} 
		catch (SQLException e) {
			validationResult = false;
			errorBuilder.append("sql error while validating user login");
		}
		
		if (user.getPassword() == null) {
			validationResult = false;
			errorBuilder.append("password is required");
		}
		else {
			if (user.getPassword().length() > 50) {
				validationResult = false;
				errorBuilder.append("password length must be < 50");
			}
		}
		
		if (!validationResult) {
			errorMessages = errorBuilder.toString();
		}
		
		return validationResult;
	}

	@Override
	public String getValidationErrorMessage() {
		return errorMessages;
	}

}
